<!-- eslint-disable vue/no-use-v-if-with-v-for -->
<template>
    <div class="sys-org-container">


        <div style="width: 100%;">
            <screeningCondition :inquireInfo="state.inquireInfo" @getChildren="getData"></screeningCondition>
        </div>

        <el-card class="full-table" shadow="hover" style="margin-top: 5px">
            <el-table :data="state.tableData" v-loading="state.loading" border highlight-current-row
                @current-change="handleRowChange" :header-cell-style="{
                    background: 'var(--el-color-primary)',
                    height: '55px', color: '#fff', border: '1px solid #fff', fontWeight: 'bold', fontSize: '13px'
                }" :cell-style="{ padding: '2px' }" class="el-table">
                <el-table-column type="expand">
                    <template #default="props">
                        <div v-if="props.row.subWcsTask && props.row.subWcsTask.length > 0">

                            <el-table :data="props.row.subWcsTask" align="left" :style="{ paddingLeft: '70px' }"
                                :border="true" :header-cell-style="{
                                    background: 'var(--el-color-primary)'
                                    , color: '#fff', fontWeight: 'bold', fontSize: '13px'
                                }">
                                <el-table-column label="子任务ID" prop="orderId" width="120" align="center" />

                                <el-table-column label="任务名称" prop="taskName" width="160" align="center" />
                                <el-table-column label="子任务序号" prop="subWcsTaskSeq" width="100" align="center" />
                                <el-table-column label="路径" prop="detail.taskPath" width="120" align="center"
                                    v-if="props.row.subWcsTask[0].detail !== null">
                                </el-table-column>
                                <el-table-column label="子任务状态" prop="detail.taskState" width="120" align="center"
                                    v-if="props.row.subWcsTask[0].detail !== null">
                                    <template v-slot="scope">
                                        <span>{{ getStatusText(scope.row.detail.taskState) }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="报错信息" prop="detail.message" width="300" align="center"
                                    v-if="props.row.subWcsTask[0].detail !== null" />
                            </el-table>
                        </div>
                    </template>

                </el-table-column>
                <el-table-column label="任务ID" prop="taskId" align="center" />
                <el-table-column label="任务名称" prop="taskName" align="center" />
                <el-table-column label="AGV编号" prop="agvNo" align="center">
                    <template v-slot="scope">
                        <span>{{ scope.row.agvNo == null ? '暂无AGV' : scope.row.agvNo }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="任务状态" prop="taskState" align="center">

                    <template v-slot="scope">
                        <span>{{ getStatusText(scope.row.taskState) }}</span>
                    </template>
                </el-table-column>

                <el-table-column label="模板ID" prop="wcsModelNo" align="center" />
                <el-table-column label="来源" prop="source" align="center" />
            </el-table>
            <el-pagination v-model:current-page="state.queryParams.page"
                                v-model:page-size="state.queryParams.pageSize" :page-sizes="[5, 10, 15, 20]"
                                layout="->,total, sizes, prev, pager, next, jumper" :total="state.total"
                                @size-change="handleSizeChange" @current-change="handleCurrentChange" :small="true" />
        </el-card>




        <el-drawer v-model="addDrawer" title="新增任务" :append-to-body="true" size="30%">
            <el-form :model="state.ruleForm2" ref="ruleFormRef" label-width="auto" class="fl">
                <el-form-item label="订单号">
                    <el-input v-model="state.ruleForm2.taskNo" placeholder="订单号" clearable />
                </el-form-item>
                <!-- 请求对应编号的名称 -->
                <el-form-item label="任务名称">
                    <el-input v-model="state.ruleForm2.taskName" placeholder="任务名称" clearable />
                </el-form-item>
                <el-form-item label="模板" prop="modelNo"
                    :rules="[{ required: true, message: '点位数不能为空', trigger: 'blur' }]">
                    <el-select v-model="state.ruleForm2.modelNo" filterable clearable class="w100"
                        @change="handlechange">
                        <el-option v-for="item in state.modelNoList" :key="item" :label="item"
                            :value="item"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="设备编号">
                    <el-input v-model="state.ruleForm2.agvNo" placeholder="设备编号" clearable />
                </el-form-item>

                <el-form-item label="优先级">
                    <el-input v-model="state.ruleForm2.priority" placeholder="优先级" clearable />
                </el-form-item>
                <el-form-item label="路径" prop="positions"
                    :rules="[{ required: true, message: '任务点不能为空', trigger: 'blur' }]">
                    <el-input v-model="state.ruleForm2.positions" placeholder="任务点请按英文逗号分隔" clearable />
                </el-form-item>
            </el-form>
        </el-drawer>

    </div>
</template>
<script lang="ts" setup name="Warehouse">
import { onMounted, reactive, ref } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { getAPI } from '/@/utils/axios-utils';
import screeningCondition from '/@/views/tools/screeningCondition.vue'

import { WcsApi } from '/@/api/wh';
import { SysDictDataApi } from '/@/api-services/api';

const addDrawer = ref(false);
const state = reactive({
    loading: false,
    tableData: [

    ],
    queryParams: {
        wcsTemLogicNo: '',
        wcsTaskName: undefined,
        page: 1,
        pageSize: 20,
    },
    dataonLineListSelections: [],
    ruleForm2: {
        id: 0,
        taskNo: "",
        taskName: "",
        agvNo: "",
        taskState: "",
        priority: 6,
        modelNo: "",
        source: "",
        positions: ""
    },
    modelNoList: [],
    total: 3,
    inquireInfo: [
        {
            label: "模板编号",
            value: "",
            key: "wcsTemLogicNo",
            options: [],
            type: 'input'

        },
        {
            label: "任务名称",
            value: "",
            key: "wcsTaskName",
            options: [],
            type: 'input'

        }

    ],
    //agv字典状态
    statusLists: [],
    //保留用户输入的筛选框内的请求条件
    value: {}
});
onMounted(async () => {
    let resDicData = await getAPI(SysDictDataApi).apiSysDictDataDataListCodeGet('AGVstatus_type');
    state.statusLists = resDicData.data.result;
    console.log(state.statusLists);
    getData(state.queryParams);
    //请求接口获得模态框中类型列表的数据，赋值给orgTypeList=tableData
})
const getStatusText = (status: number) => {
    return state.statusLists[status].value || '未知状态';
}
const currentRow = ref()
const handleSwitch = (row) => {

}
const getCorrespondStatus = (v) => {

    const item = state.statusLists.filter(item => item.code == v);

    return item[0] ? item[0].value : null;
    // console.log(a);
    // return a[0].value
}
// // 查询操作
const getData = (value) => {

    state.value = value
    let params = {
        page: state.queryParams.page,
        pagesize: state.queryParams.pageSize,
        wcsTemLogicNo: value.wcsTemLogicNo,
        wcsTaskName: value.wcsTaskName

        // orderId: value.orderId,
        // state: value.state
    }
    WcsApi().checkTask(params)

        .then(function (res) {
            state.tableData = res.data.result.items;
            console.log(state.tableData);
            state.total = res.data.result.total;
        })
        .catch(function (error) {
            console.log(error);
        });
};

const selectionLineChangeHandle = (val) => {
    state.dataonLineListSelections = val
}
const handleToCreateTask = async () => {

    let params = {
        'modelNo': state.ruleForm2.modelNo,
        'taskDetail': [{
            'positions': state.ruleForm2.positions
        }]
    };

    await WmsApi().agvPageAdd(params)

        .then(function (response) {

            ElMessage.success('任务下达成功')
            getData(state.queryParams);
        })
        .catch(function (error) {
            console.log(error);
        });

}


// 打开新增页面
const openAddOrg = () => {
    state.ruleForm2 = {};
    addDrawer.value = true;
};
const submit = () => {

}
const timeConsuming = (a, b) => {
    var d = new Date(a).getTime();
    var e = new Date(b).getTime();
    var result = (d - e) / 1000 / 60


    return result;
}
const handlechange = (val) => {
    state.ruleForm2.modelNo = val;
    state.ruleForm2.taskName = val;
}
const cancelTask = async (row) => {
    ElMessageBox.confirm(`确定取消该任务吗：【${row.taskName}】?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(async () => {
            await WmsApi().agvCancel({
                "taskNo": row.taskNo
            })
                .then(function (res) {
                    ElMessage.success('取消成功');
                    getData(state.queryParams);
                })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消取消任务',
            })
        });
}

const handleSizeChange = (val) => {
    state.queryParams.pageSize = val;
    state.queryParams.wcsTaskName = state.value.wcsTaskName;
    state.queryParams.wcsTemLogicNo = state.value.wcsTemLogicNo;


    getData(state.queryParams);
};
const handleCurrentChange = (newVal) => {

    state.queryParams.page = newVal;
    state.queryParams.wcsTaskName = state.value.wcsTaskName;
    state.queryParams.wcsTemLogicNo = state.value.wcsTemLogicNo;


    getData(state.queryParams);
};
const handleRowChange = (val) => {
    currentRow.value = val;
}

</script>
<style lang="scss" scoped>
.lie .el-form-item {
    margin-bottom: 30px;
    font-size: 16px;
}

.fl {

    width: 60%;
    margin: 20px 80px;

}

.hang {
    display: flex;
}

.radius {
    height: 22px;
    width: 164.75px;
    border: 1px solid var(--el-border-color);
    border-radius: 5px;
    background-color: #ddd;
    padding-left: 5px;
    padding-top: -4px;
    color: #afabb9;
    background-color: #f5f7fa;

}

.container {
    margin-top: 15px;
    width: 100%;
    display: flex;
    flex-direction: column;
    height: calc(100% - 82px);
}

.table {
    width: 100%;
    flex: 1;
    height: 100%;
}

.el-table {
    width: 100%;
}

.extra {
    width: 170px;
    height: 80px;

    :deep(.el-textarea__inner) {
        height: 80px;
    }
}
</style>